<template>
  <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
    <el-form-item label="用户昵称" prop="nick_name">
      <el-input v-model="form.nick_name" maxlength="32" />
    </el-form-item>
    <el-form-item label="手机号码" prop="phone">
      <el-input v-model="form.phone" maxlength="11" />
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="form.email" maxlength="64" />
    </el-form-item>
    <el-form-item label="性别">
      <el-radio-group v-model="form.sex">
        <el-radio value="0">男</el-radio>
        <el-radio value="1">女</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" :loading="submitting" @click="submit">保存</el-button>
      <el-button type="danger" @click="close">关闭</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
  import { updateProfileApi } from '@/api/common'

  const user = defineModel()

  const { proxy } = getCurrentInstance()

  const form = ref({ nick_name: undefined, phone: undefined, sex: undefined, email: undefined })
  const rules = ref({
    nick_name: [{ required: true, message: '用户昵称不能为空', trigger: 'blur' }],
    email: [
      { required: true, message: '邮箱地址不能为空', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
    ],
    phone: [
      { required: true, message: '手机号码不能为空', trigger: 'blur' },
      { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ]
  })

  // 回显当前登录用户信息
  watch(
    user,
    user => {
      form.value = proxy.dataToForm(form.value, user)
    },
    { immediate: true }
  )

  /** 提交按钮 */
  const formRef = useTemplateRef('formRef')
  const submitting = ref(false)
  function submit() {
    formRef.value.validate(valid => {
      if (!valid || submitting.value) return
      submitting.value = true
      updateProfileApi(form.value)
        .then(() => {
          proxy.$modal.msgSuccess('修改成功')
          user.value.phone = form.value.phone
          user.value.email = form.value.email
        })
        .finally(() => {
          submitting.value = false
        })
    })
  }

  /** 关闭按钮 */
  function close() {
    proxy.$tab.closePage()
  }
</script>
